// pages/tabBar3/tabBar3.js
const app = getApp()
Page({
  data: {
    canvasShow: false,
    show: false,
    showAddSheet: false,
    canHideCommentInput: true,
    showCommentInput: false,
    comment_item_id: '',
    comment_item_index: 0,
    animationData: {},
    textareaWidth: 0,
    textareaP: '',
    admin:false,
    TabCur: 0,
    well0: [],
    well1: [],
    well2: [],
    well: {
      _openid: '',
      nickName: '',
      avatarUrl: '',
      cloud_imageID: [], //展现页面的data还需要存临时链接
      tempImageUrl: [],
      description: '',
      tag: 0,
      tag: 0,
      look: 1,
      like: 0,
      comments: [],
      publish_time: 0,
      time: '',
      formId: ''
    },
    comment: {
      _openid: '',
      nickName: '',
      avatarUrl: '',
      content: '',
      time: ''
    }

  },
  onShow(){
    this.setData({
      admin:app.globalData.admin
    })
  },
  onReady() {
    //console.log("ready")
    this.setData({
      show: true
    })
    this.getFromDB(0, 0)//tag,skip
  },
  onLoad: function (options) {
    qq.showShareMenu({
      showShareItems: ['qq', 'qzone', 'wechatFriends', 'wechatMoment']
    })
    //console.log("s")
    if (app.globalData.userInfo == null) {
      qq.getUserInfo({
        success(res) {
          app.globalData.userInfo = res.userInfo
          // //console.log(res)
        },
        fail(msg) {
          qq.redirectTo({
            url: "/pages/welcome/welcome"
          })
        }
      })
    }
    this.setOpenId()
  },
  setOpenId() {
    var that = this
    var s = setInterval(function () {
      if (that.data.openid) {
        clearInterval(s)
      } else {
        that.setData({
          openid: app.globalData.openid
        })
      }
    }, 100)
  },
  like(e) {
    var id = e.currentTarget.dataset.like_item_id
    var index = e.currentTarget.dataset.like_item_index
    var that = this
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databaseupdate?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"well\").doc(\"" + id + "\").update({\
         data: {\
        like: db.command.inc(1)\
      }\
    })"
      },
      success(res) {
        //console.log(res)
        qq.showToast({
          title: "点赞成功"
        })
        switch (that.data.TabCur) {
          case 0:
            that.data.well0[index].like++
            that.setData({
              well0: that.data.well0
            })
            break;
          case 1:
            that.data.well1[index].like++
            that.setData({
              well1: that.data.well1
            })
            break;
          case 2:
            that.data.well2[index].like++
            that.setData({
              well2: that.data.well2
            })
            break;
        }
      },
      fail() {
        qq.showToast({
          icon: 'none',
          title: '请检查网络！'
        })
      }
    })
  },

  comment(e) {
    //console.log(e)
    this.setData({
      showCommentInput: true,
      comment_item_id: e.currentTarget.dataset.comment_item_id,
      comment_item_index: e.currentTarget.dataset.comment_item_index
    })
  },
  inputComment(e) {
    this.setData({
      'comment.content': e.detail.value
    })
  },
  doComment() {
    this.setData({
      canHideCommentInput: false,
    })
    //console.log("E")
    if (this.data.comment.content.length > 0) {
      qq.showLoading({
        title: "评论中"
      })
        var time = new Date()
      var theTime = time.getFullYear() + '年' + (time.getMonth() + 1) + "月" + time.getDate() + "日 "
      if(time.getHours()<10){
        theTime+='0'
      }
      theTime+=time.getHours()+":"
      if(time.getMinutes()<10){
        theTime+='0'
      }
      theTime+=time.getMinutes()
      this.setData({
        'comment.nickName': app.globalData.userInfo.nickName,
        'comment.avatarUrl': app.globalData.userInfo.avatarUrl,
        'comment._openid': app.globalData.openid,
        'comment.publish_time': new Date().getTime(),
        'comment.time': theTime
      })//成功之后需要隐藏comment
      this.sendComment()
    } else {
      qq.showToast({
        icon: 'none',
        title: '你想让我看什么呢~'
      })
    }
  },
  sendComment() {
    var id = this.data.comment_item_id
    var comment = this.data.comment
    var that = this
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databaseupdate?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"well\").doc(\"" + id + "\").update({\
        data: {\
               comments: db.command.push(["+ JSON.stringify(comment) + "])\
               }\
         })"
      },
      success(res) {
        //console.log(res)
        qq.hideLoading()
        qq.showToast({
          title: "评论成功"
        })
        var index = that.data.comment_item_index
        var comment =Object.assign({}, that.data.comment)
        switch (that.data.TabCur) {
          case 0:
            that.data.well0[index].comments.push(comment)
            that.setData({
              well0: that.data.well0
            })
            break;
          case 1:
            that.data.well1[index].comments.push(comment)
            that.setData({
              well1: that.data.well1
            })
            break;
          case 2:
            that.data.well2[index].comments.push(comment)
            that.setData({
              well2: that.data.well2
            })
            break;
        }
        that.setData({
          'comment.content': ''
        })
      }
    })
  },
  hideCommentInput() {
    var that = this
    setTimeout(function () {
      if (that.data.canHideCommentInput) {
        that.setData({
          showCommentInput: false
        })
      }
    }, 150)
    setTimeout(function () {
      that.setData({
        canHideCommentInput: true,
        showCommentInput: false,
      })
    }, 700)
  },

  deleteComment(e) {
    var that = this
    qq.showModal({
      title: "确定删除？",
      content: '你将删除此评论。',
      success(res) {
        if (res.confirm) {
          qq.showLoading({
            title: "删除中"
          })
          that.doDeleteComment(e)
        }
      }
    })
  },


  doDeleteComment(e) {
    var item_id = e.currentTarget.dataset.item_id
    var item_index = e.currentTarget.dataset.item_index
    var comment_index = e.currentTarget.dataset.comment_index
    var comments = []
    //console.log(item_id, item_index, comment_index)
    var that = this
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databasequery?access_token=' + app.globalData.access_token,
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"well\").doc(\"" + item_id + "\").get()"
      },
      success(res) {
        // //console.log(res)
        comments = JSON.parse(res.data.data[0]).comments
        comments.splice(comment_index, 1)///////////组成了新的
        var data = {
          comments: comments
        }
        qq.request({/////////////网络更新
          url: 'https://api.weixin.qq.com/tcb/databaseupdate?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
          header: {
            'content-type': 'application/json' // 默认值
          }, method: "post",
          data: {
            "env": app.globalData.myEnv,
            "query": "db.collection('well').doc(\"" + item_id + "\").update({data: " + JSON.stringify(data) + "})"
          },
          success(res) {
            qq.hideLoading()
            qq.showToast({
              title: "删除成功"
            })
            switch (that.data.TabCur) {
              case 0:
                that.data.well0[item_index].comments = comments
                that.setData({
                  well0: that.data.well0
                })
                break;
              case 1:
                that.data.well1[item_index].comments = comments
                that.setData({
                  well1: that.data.well1
                })
                break;
              case 2:
                that.data.well2[item_index].comments = comments
                that.setData({
                  well2: that.data.well2
                })
                break;
            }
          },
          fail() {
            qq.hideLoading()
            qq.showToast({
              icon: 'none',
              title: '请检查网络！'
            })
          }
        })
      }
    })

  },
  addSelect(e) {
    this.setData({
      'well.tag': e.currentTarget.dataset.id - 0,
    })
  },
  ableAddFriend(e) {//已完成
    var that = this
    qq.getSetting({
      success(res) {
        //console.log(res)
        if (!res.authSetting['setting.addFriend']) {
          qq.authorize({
            scope: 'setting.addFriend',
            success() {
              app.globalData.ableAddFriend = true
            },
            fail() {
              setTimeout(function () {
                that.ableAddFriend();
              }, 7000)
              qq.showModal({
                title: "请求授权",
                content: "为了让其他人了解你,请授权【允许向我发起加好友】请求和【用户信息】",
                showCancel: false,
                confirmText: "去授权",
                success() {
                  qq.openSetting()
                }
              })
            }
          })
        }
      }
    })
  },
  showAdd() {
    const animation = qq.createAnimation({
      duration: 200,
      timingFunction: 'ease',
    })
    animation.rotate(180).step()
    this.setData({
      animationData: animation.export(),
      showAddSheet: true,
      textareaWidth: 100,
      'well.description': ''
    })
    // this.ableAddFriend()
  },
  hideAdd() {
    const animation = qq.createAnimation({
      duration: 200,
      timingFunction: 'ease',
    })
    animation.rotate(0).step()
    this.setData({
      animationData: animation.export(),
      showAddSheet: false,
      "textareaWidth": 0,
      'well.description': ''
    })
  },
  tabSelect(e) {
    var tag = e.currentTarget.dataset.id - 0
    this.setData({
      TabCur: tag
    })
    if (tag == 0 && this.data.well0.length == 0) {
      this.getFromDB(0, 0)
    } else if (tag == 1 && this.data.well1.length == 0) {
      this.getFromDB(1, 0)
    } else if (tag == 2 && this.data.well2.length == 0) {
      this.getFromDB(2, 0)
    }
  },
  onPullDownRefresh() {
    switch (this.data.TabCur) {
      case 0:
        this.setData({
          well0: []
        })
        this.getFromDB(0, 0)
        break;
      case 1:
        this.setData({
          well1: []
        })
        this.getFromDB(1, 0)
        break;
      case 2:
        this.setData({
          well2: []
        })
        this.getFromDB(2, 0)
        break;
    }
  },
  ChooseImage() {
    var that = this
    qq.chooseImage({
      count: 4,
      sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.zipImg(0, res.tempFilePaths)
      }
    });
  },
  zipImg(index, tempFilePaths) {
    var that = this
    if (index < tempFilePaths.length) {/////对每一个进行循环，获取连接后写入data
      qq.getImageInfo({
        src: tempFilePaths[index],
        success(res) {
          //console.log(res)
          var targetHeight = res.height
          var targetWidth = res.width
          var maxWidth = 500
          var maxHeight = 1200 //2100以内 按宽度1000，高度自适应压缩，
          //console.log(targetHeight, targetWidth)

          if (targetWidth > maxWidth || targetHeight > maxHeight) {
            if ((targetWidth / targetHeight) > (maxWidth / maxHeight)) {
              targetHeight = Math.round(maxWidth * (targetHeight / targetWidth));
              targetWidth = maxWidth;
              // //console.log(">") 顺序什么都不能改变，易错
            } else {
              targetWidth = Math.round(maxHeight * (targetWidth / targetHeight));
              targetHeight = maxHeight;
            }
          }
          //console.log(targetHeight, targetWidth)

          that.setData({
            targetWidth: targetWidth,
            targetHeight: targetHeight,
            canvasShow: true
          })
          setTimeout(function () {
            const ctx = qq.createCanvasContext('canvas');
            ctx.drawImage(tempFilePaths[index], 0, 0, targetWidth, targetHeight);
            ctx.draw(false, function () {
              qq.canvasToTempFilePath({
                canvasId: ('canvas'),
                fileType: "jpg",
                quality: 0.5,
                destWidth: targetWidth,
                destHeight: targetHeight,
                success(res) {
                  that.setData({
                    'well.tempImageUrl': that.data.well.tempImageUrl.concat(res.tempFilePath),
                    canvasShow: false
                  })
                  setTimeout(function () {
                    index++
                    that.zipImg(index, tempFilePaths);
                    //console.log(res)
                  },100)
                }
              })
            })
          }, 100)

        }
      })
    }
  },
  inputDescription(e) {
    this.setData({
      'well.description': e.detail.value
    })
  },
  // look+1
  look(tag, skip) {
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databaseupdate?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection('well').limit(10).skip(" + skip + ").where({tag:" + tag + "})\
        .update({\
          data: { look: db.command.inc(1)}\
        })"
      },
      success(res) {
      },
    })
  },
  deleteWell(e) {
    //console.log(e)
    var that = this
    qq.showModal({
      title: "确定删除？",
      content: "你将删除此动态及其相关图片、评论、点赞、浏览量等信息。",
      success(res) {
        if (res.confirm) {
          qq.showLoading({
            title: "删除中"
          })
          var c = e.currentTarget.dataset
          that.doDeleteWell(c.item_id, c.file_list, c.item_index)
        }
      }
    })
  },
  doDeleteWell(item_id, file_list, index) {
    //console.log(index)
    var that = this
    qq.request({//删除图片
      url: 'https://api.weixin.qq.com/tcb/batchdeletefile?access_token=' + app.globalData.access_token,
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: "post",
      data: {
        "env": app.globalData.myEnv,
        "fileid_list": file_list
      },
      success(res) {
        qq.request({//删除数据库
          url: 'https://api.weixin.qq.com/tcb/databasedelete?access_token=' + app.globalData.access_token,
          header: {
            'content-type': 'application/json' // 默认值
          }, method: "post",
          data: {
            "env": app.globalData.myEnv,
            "query": "db.collection(\"well\").doc(\"" + item_id + "\").remove()"
          },
          success(res) {
            qq.hideLoading()
            qq.showToast({
              title: "删除成功"
            })
            switch (that.data.TabCur) {
              case 0:
                //console.log(index)
                that.data.well0.splice(index, 1)
                that.setData({
                  well0: that.data.well0
                })
                break;
              case 1:
                that.data.well1.splice(index, 1)
                that.setData({
                  well1: that.data.well1
                })
                break;
              case 2:
                that.data.well2.splice(index, 1)
                that.setData({
                  well2: that.data.well2
                })
                break;
            }
          },
          fail() {
            qq.hideLoading()
            qq.showToast({
              icon: 'none',
              title: '请检查网络！'
            })
          }
        })
      },
      fail() {
        qq.hideLoading()
        qq.showToast({
          icon: 'none',
          title: '请检查网络！'
        })
      }
    })

  },
   onReachBottom: function () { // 已完成
   console.log("bottom")
    switch (this.data.TabCur) {
      case 0:
        var skip = this.data.well0.length
        this.getFromDB(0, skip)
        break;
      case 1:
        var skip = this.data.well1.length
        this.getFromDB(1, skip)
        break;
      case 2:
        var skip = this.data.well2.length
        this.getFromDB(2, skip)
        break;
    }
  },
  // 获取
  getFromDB(tag, skip) {
    qq.showLoading({
      title: '加载中'
    })
    var that = this
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databasequery?access_token=' + app.globalData.access_token,
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"well\").limit(10).skip(" + skip + ").where({tag:" + tag + "}).orderBy(\"publish_time\", \"desc\").get()"
      },
      success(res) {
        //console.log(res)
        var list = res.data.data //数组中的内容需要在下面转成对象
        qq.hideLoading()
        qq.stopPullDownRefresh()
        if (list.length > 0) {//如果没有请求完
          var newList = []
          for (var i = 0; i < list.length; i++) {
            newList[i] = JSON.parse(list[i])
          }
          that.getFileUrl(tag, newList)//需要加载图片的

        } else {//如果请求完了
          qq.showToast({
            title: '已加载全部'
          })
        }
      },
      fail() {
        qq.hideLoading()
        qq.showToast({
          icon: 'none',
          title: '请检查网络！'
        })
      }
    })
    this.look(tag, skip)
  },

  getFileUrl(tag, list) {
    //console.log("ss")
    var that = this
    var now = 0;
    var newList = []
    for (var i = 0; i < list.length; i++) {
      (function () {
        var t = i
        var item = list[t]
        if (item.cloud_imageID.length != 0) {
          var file_list_post = []//拼装file_list
          //console.log(item)
          for (var j = 0; j < item.cloud_imageID.length; j++) {
            file_list_post.push({
              "fileid": item.cloud_imageID[j],
              "max_age": 8640000
            })
          }
          qq.request({//请求拼装好的
            url: 'https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=' + app.globalData.access_token,
            header: {
              'content-type': 'application/json' // 默认值
            }, method: "post",
            data: {
              "env": app.globalData.myEnv,
              "file_list": file_list_post
            },
            success(res) {
              var file_list_return = res.data.file_list
              //console.log(res)
              var tempImageUrl = []
              for (var k = 0; k < file_list_return.length; k++) {
                tempImageUrl.push(file_list_return[k].download_url)
              }
              item.tempImageUrl = tempImageUrl
              newList[t] = item
              //console.log(newList)
              now++
            },
            fail() {
              qq.hideLoading()
              qq.showToast({
                icon: 'none',
                title: '请检查网络！'
              })
            }
          })
        } else {
          newList[t] = item
          now++
        }
      }(i))
    }
    var s = setInterval(function () {
      if (now == list.length) {
        //console.log(newList)
        switch (tag) {
          case 0:
            that.setData({
              well0: that.data.well0.concat(newList)
            })
            break;
          case 1:
            that.setData({
              well1: that.data.well1.concat(newList)
            })
            break;
          case 2:
            that.setData({
              well2: that.data.well2.concat(newList)
            })
            break;
        }
        clearInterval(s)
      }
    })
  },


  // 上传
  doSubmit(e) {
    if (this.data.well.description.length < 3 && this.data.well.tempImageUrl.length < 1) {
      qq.showToast({
        icon: "none",
        title: "你打算让我看什么呢～"
      })
    } else {

      var time = new Date()
      var theTime = time.getFullYear() + '年' + (time.getMonth() + 1) + "月" + time.getDate() + "日 "
      if(time.getHours()<10){
        theTime+='0'
      }
      theTime+=time.getHours()+":"
      if(time.getMinutes()<10){
        theTime+='0'
      }
      theTime+=time.getMinutes()

      this.setData({
        'well.nickName': app.globalData.userInfo.nickName,
        'well.avatarUrl': app.globalData.userInfo.avatarUrl,
        'well.publish_time': new Date().getTime(),
        'well._openid': app.globalData.openid,
        'well.formId': e.detail.formId,
        'well.time': theTime,
      })
      this.uploadFile()
    }
    //console.log(e)
  },
  uploadFile() {
    var i = 0 //正在上传第i
    var j = 0 //已经上传j
    var that = this
    var num = that.data.well.tempImageUrl.length
    qq.showLoading({
      title: '上传' + i + '/' + num
    })
    var s = setInterval(function () {
      //console.log(i, j, num)
      if (j == num) {
        that.addToDB()
        clearInterval(s)
      } else if (j == i) {
        qq.hideLoading()
        qq.showLoading({
          title: '上传' + i + '/' + num
        })
        i++;//此时i>j
        //下面进行上传图片，完成第i张上传后，j++，此时j=i
        const filePath = that.data.well.tempImageUrl[i - 1]//第一张为0
        const cloudPath = 'well/' + app.globalData.openid + new Date().getTime() + filePath.match(/\.[^.]+?$/)[0]
        var url = 'https://api.weixin.qq.com/tcb/uploadfile?access_token=' + app.globalData.access_token
        //console.log(url)
        qq.request({////////////////////////获取cos的url
          url,
          header: {
            'content-type': 'application/json' // 默认值
          },
          data: {
            "env": app.globalData.myEnv,
            "path": cloudPath
          },
          method: "POST",
          success(res1) {//////////////////////////通过cos上传
            //console.log(1, res1)
            qq.uploadFile({
              url: res1.data.url,
              filePath,
              name: 'file',
              header: {
                "Content-Type": "multipart/form-data"//记得设置
              },
              formData: {
                key: cloudPath,
                "Signature": res1.data.authorization,
                "x-cos-security-token": res1.data.token,
                "x-cos-meta-fileid": res1.data.cos_file_id
              },
              success(res2) { ////////////////////添加到数据库
                that.setData({
                  'well.cloud_imageID': that.data.well.cloud_imageID.concat(res1.data.file_id)
                })
                j++
                //console.log(res2)
              }, fail(msg) {
                //console.log(msg)
              }
            })
            //console.log(res1)
          }
        })
      }
    }, 10)
  },
  addToDB() {
    var data = JSON.stringify(this.data.well)
    var that = this
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databaseadd?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"well\").add({\
            data: "+ data + "\
        })"
      },
      success(res) {
        qq.hideLoading()
        qq.showToast({
          title: "上传成功"
        })
        var well = [that.data.well]
        switch (that.data.TabCur) {
          case 0:
            that.setData({
              well0: well.concat(that.data.well0)
            })
            break;
          case 1:
            that.setData({
              well1: well.concat(that.data.well1)
            })
            break;
          case 2:
            that.setData({
              well2: well.concat(that.data.well2)
            })
            break;
        }
        that.setData({
          well: {
            _openid: '',
            nickName: '',
            avatarUrl: '',
            cloud_imageID: [], //展现页面的data还需要存临时链接
            tempImageUrl: [],
            description: '',
            tag: 0,
            look: 1,
            like: 0,
            comments: [],
            publish_time: 0,
            time: '',
            formId: ''
          }
        })
        that.hideAdd()
      }
    })
  },


  ViewImage(e) {
    qq.previewImage({
      urls: this.data.well.tempImageUrl,
      current: e.currentTarget.dataset.url
    });
  },
  ViewWellImage(e) {
    qq.previewImage({
      urls: e.currentTarget.dataset.imgs,
      current: e.currentTarget.dataset.img
    });
  },
  DelImg(e) {
    this.data.well.tempImageUrl.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      'well.tempImageUrl': this.data.well.tempImageUrl
    })
  },

})